package cn.asterly.cicada.common.utils;

import cn.asterly.cicada.common.exception.IPErrorException;
import cn.asterly.cicada.common.model.IpInfo;
import cn.asterly.cicada.common.model.IpWeatherResult;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sun.javafx.scene.paint.GradientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;


/**
 * @Description
 * @author likun
 * @Date 19:02 2019-02-28
 * @Param 
 * @return 
 **/
public class IPInfoUtil {

    private static final Logger log = LoggerFactory.getLogger(IPInfoUtil.class);
    /*百度IP信息查询的key*/
    private final static String WEBIPKEY = "2atIkpd8LoOV4cw6gUvwVlK4pWdQ7lud";
    /**执行的标准*/
    private final static String COOR="bd09ll";
    /**api地址前缀*/
    private final static String APIPREFIX="https://api.map.baidu.com/location/ip?ip=";
    /**api地址后缀*/
    private final static String APISUFIX="&ak="+WEBIPKEY+"&coor="+COOR;
    /**
     * IP地址定位城市信息
     */
    private final static String GET_WEATHER="https://api.map.baidu.com/location/ip?ip=123.19.222.222&ak="+WEBIPKEY+"&coor=bd09ll\n";

    /**
     * 获取客户端IP地址
     * @param request 请求
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.indexOf(",") != -1) {
            String[] ipWithMultiProxy = ip.split(",");

            for(int i = 0; i < ipWithMultiProxy.length; ++i) {
                String eachIpSegement = ipWithMultiProxy[i];
                if (!"unknown".equalsIgnoreCase(eachIpSegement)) {
                    ip = eachIpSegement;
                    break;
                }
            }
        }

        return ip;
    }

    /**
     * 获取IP返回地理天气信息
     * @param ip ip地址
     * @return
     */
    public static String getIpInfo(String ip){
        if(null != ip){
            String url = GET_WEATHER + ip;
            String result= HttpUtil.sendGet(url);
            return result;
        }
        return null;
    }

    /**
     * @Description  判断是否为内网IP
     * @Date 21:44 2019-03-01
     * @Param
     * @return
     **/
    public static boolean isInnerIp(String ip){
        //判断Ip是否为内网Ip
        return Pattern.matches("^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$", ip);
    }

    /**
     * 获取IP返回地理信息
     * @param ip ip地址
     * @return
     */
    public static String getIpCity(String ip){

            if(null != ip) {
                //获取Ip地址信息
                String address = HttpUtil.sendGet(getapiUrl(ip));
//                System.out.println(address);
                JsonObject jsonObject= (JsonObject) new JsonParser().parse(address);
        //            String city = jsonObject.get("content").getAsJsonObject().get("address").getAsString();
                String city=new JsonParser()
                        .parse(address)
                        .getAsJsonObject()
                        .get("content")
                        .getAsJsonObject()
                        .get("address")
                        .getAsString();
                return city;

            }else{
                throw new NullPointerException("ip地址为空,将返回默认地址");
            }

    }

    /**根据ip返回一个百度请求的URL地址*/
    public static String getapiUrl(String ip){
        return APIPREFIX+ip+APISUFIX;
    }

    public static void main(String[] args) {
        String ip="192.168.235.111";
//        String s = getapiUrl("123.207.19.222");
//        String ipCity = getIpCity("120.79.235.35");
//        System.out.println(ipCity);

//        String jsnstr="{\"address\":\"CN|\\u5e7f\\u4e1c|\\u5e7f\\u5dde|None|TENCENT|0|0\",\"content\":{\"address_detail\":{\"province\":\"\\u5e7f\\u4e1c\\u7701\",\"city\":\"\\u5e7f\\u5dde\\u5e02\",\"district\":\"\",\"street\":\"\",\"street_number\":\"\",\"city_code\":257},\"address\":\"\\u5e7f\\u4e1c\\u7701\\u5e7f\\u5dde\\u5e02\"," +
//                "\"point\":{\"y\":\"23.113899849892\",\"x\":\"113.30119382051\"}},\"status\":0}";
//
//        JsonObject jsonObject= (JsonObject) new JsonParser().parse(jsnstr);
//        String address = jsonObject.get("content").getAsJsonObject().get("address").getAsString();
//        System.out.println(address);
        boolean matches = Pattern.matches("^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$", ip);
        System.out.println(matches);
    }
}
